var firstLoad = true;
//flag to indicate if the first loading occurs, datepicker is still in creation progress
//we have to set default search criteria.
var firstDatePickerLoad = true; 

var listEditedRowID = new Array();

var lastEditedRow = -1;

function getCurrentCondition4ReleasedHold() {
	// turn on first load flag
	firstLoad = true;
	
	// set search parameters.
	var customername = $("#customername").val();
	var prios = [];
	$("input[name='priority']:checked").each(
		function(){
			prios.push($(this).val());
		}
	);
	var prodarea = [];
	$("input[name='prodarea']:checked").each(
		function(){
			prodarea.push($(this).val());
		}
	);
	var prodarea = [];
	$("input[name='prodarea']:checked").each(
		function(){
			prodarea.push($(this).val());
		}
	);
	var department = [];
	$("input[name='department']:checked").each(
		function(){
			department.push($(this).val());
		}
	);
	var holdcode = $("select[name=selectedHC]").val();
	holdcode = $("select[name=selectedHC] option:selected").text() + '+=+' + holdcode;
	
	var holdcodereclas = $("select[name=selectedHCReclass]").val();
	holdcodereclas = $("select[name=selectedHCReclass] option:selected").text() + '+=+' + holdcodereclas;
	
	var holdreason = $('#holdcomment').val();
	var holdreclasreason = $('#holdcommentreclass').val();
	
	if (firstDatePickerLoad) {
		// turn off flag
		firstDatePickerLoad = false;
		
		holdEndTo = printDate(new Date());
		var from = new Date();
		from.setMonth(from.getMonth() - 3);
		holdEndFrom = printDate(from);

	} else {
		// set search parameters.
		holdEndFrom = printDate($("#holdend_from_datepicker").datepicker("getDate"));
		holdEndTo = printDate($("#holdend_to_datepicker").datepicker("getDate"));
	}
	
	return {priority: prios, prodarea: prodarea, 
		department: department, customername: customername,
		holdcode: holdcode, holdreason: holdreason,
		holdcodereclas: holdcodereclas, holdreclasreason: holdreclasreason,
		holdendfrom: holdEndFrom, holdendto: holdEndTo};
}

function populateFinishedHoldData(finishedHoldModel) {
	
	var mygrid = jQuery("#s3list")
		.jqGrid(
				{
					url : 'searchReleasedHold.do',
					datatype : "json",
					postData: getCurrentCondition4ReleasedHold(),
					
					height: 456,
					colNames : finishedHoldModel.colNames,
					colModel : finishedHoldModel.colModel,
					rowNum : 200,
					width : 1060,
					mtype : "POST",
					rowList : [ 200, 300, 500 ],
					pager : '#s3pager',
					sortname : finishedHoldModel.defaultSortColumn,
					viewrecords : true,
					rownumbers : true,
					sortorder : "asc",
					headertitles : true,
					gridview : true,
					scrolling: true,
					autowidth: false,
					shrinkToFit: false,
					loadonce: true,
					multiselect: true,
					editurl:'clientArray',
					//beforeSelectRow: handleMultiSelect, // handle multi select
					ignoreCase: true,
					caption:"RELEASED HOLD (" + finishedHoldModel.currentDate + ")",
					onHeaderClick: function (stat) {
				    	if(stat == 'visible' ){
				    		jQuery("#filter").css("display","none");
				    	}
					},
					beforeSelectRow: function(rowid, e){
						lastEditedRow = rowid;
						if(e.target.type == "checkbox"){
							// turn row to read only mode if row is editing mode
							if (e.target.checked == true && $("tr#"+rowid).attr("editable") == "1") {
								jQuery('#s3list').jqGrid('restoreRow', rowid);
								
								// remove edited row
								for (var j = listEditedRowID.length - 1; j >= 0; j--) {
									if (listEditedRowID[j] == rowid) {
										listEditedRowID.splice(j, 1);
									}
								}
								
								// trigger scrolling keep current view
								var gridScroll = $('div.ui-jqgrid-bdiv'); 
								gridScroll.scrollLeft(1);
							}
							return true;
						}
						return false;
				    },
					ondblClickRow: function (rowId, iRow, iCol, e)
					{
						// this row is not in edit mode
						if ($("tr#"+rowId).attr("editable") != "1" ) {
							// mark this row
							lastEditedRow = rowId;
							listEditedRowID.push(rowId);
							
							// change this row to edit mode
							jQuery("#s3list").jqGrid('editRow',rowId);
							
							var ch =  jQuery(this).find('tr#'+rowId+' input[type=checkbox]').prop('checked');
							if(ch) {
								jQuery('#s3list').jqGrid("setSelection",new String(rowId),false); 
							}
							
							//jQuery('#s3list').jqGrid("setSelection",new String(rowId),false);
						}
					},
					loadComplete: function()
					{
						listEditedRowID = new Array();
					},
					gridComplete: function() {
						var ids = jQuery('#s3list').getDataIDs();
						
						if (firstLoad && ids.length > 0) {
							//update current time
							jQuery("#s3list").setCaption("RELEASED HOLD " + displayNiceDateFormat(new Date()));
							// reset firstLoad
							firstLoad = false;
						}
						
						var ids = jQuery('#s3list').getDataIDs();
						for (var i = 0, idCount = ids.length; i < idCount; i++) {
				    		color ='';
				    		cellId = ids[i];
				    		columnName = 'P3H_HOLD_DURATION';
							val = jQuery('#s3list').jqGrid ('getCell', cellId, columnName);
							if (eval(val + finishedHoldModel.redColorCon)) {
								color = '#FE4545';
							} else if (eval(val + finishedHoldModel.yellowColorCon)) {
								color = 'yellow';
							}
							if (color !='')
								jQuery('#s3list').jqGrid('setCell',cellId,columnName,"",{'background-color':color,'color': 'black', 'background-image':'none'});
				      };
				     },
					onRightClickRow: function (rowid) {
				        jQuery("#s3list").contextMenu('rightClickMenu', {
				            bindings: {
				                'CopyRow': function(t) {
				                	var rowids = jQuery('#s3list').getGridParam('selarrrow');
				        			if (rowids) {
				        				getRowData(rowids);
				        			}
				                }
				            },
				              menuStyle: {
				                //border: '',
				                width: '165px',
				                color: '#000000'
				              },
				              itemStyle: {
				                fontFamily : 'verdana',
				                fontSize : '80%',
				                //backgroundColor : '#94AEC4',
				                color: '#000000',
				                border: 'none',
				                padding: '1px',
				                height: '15px',
				                align: 'center'
				              },
				              itemHoverStyle: {
				                color: '#FFFFFF',
				                backgroundColor: '#567F9F',
				                color: 'white',
				                border: 'none'
				              }

				        });
				    }
				});
	
	
	
	jQuery("#s3list").jqGrid('navGrid', '#s3pager', {
		edit : false,
		add : false,
		del : false,
		search : false,
		refresh : false
	});
	/*
	jQuery("#s3list").jqGrid('navButtonAdd', "#s3pager", {
		caption : "Toggle",
		title : "Toggle Search",
		buttonicon : 'ui-icon-pin-s',
		onClickButton : function() {
			mygrid[0].toggleToolbar();
		}
	});
	*/
	jQuery("#s3list").jqGrid('navButtonAdd', "#s3pager", {
		caption : "Clear",
		title : "Clear Search",
		buttonicon : 'ui-icon-refresh',
		onClickButton : function() {
			mygrid[0].clearToolbar();
			// clear updated rowId
			listEditedRowID = new Array();
		}
	});
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Export to Excel",
		buttonicon : 'ui-icon-disk',
		onClickButton : function () {
		jQuery("#s3list").jqGrid('excelExport', 
				{ url: 'exportReleasedHoldsToExcel.do'});
		}
	});
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Export to PDF",
		buttonicon : 'ui-icon-document',
		onClickButton : function () {
		jQuery("#s3list").jqGrid('excelExport', 
				{ url: 'exportReleasedHoldsToPdf.do'});
		}
	});
	
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Copy",
		buttonicon : 'ui-icon-copy',
		onClickButton : function () {
			//var rowids = jQuery("#s3list").jqGrid('getGridParam', 'selrow');
			var rowids = jQuery('#s3list').getGridParam('selarrrow');
			if (rowids) {
				getRowData(rowids);
			} else {
				alert("No selected row!!!");
			}
		}
	});
	
	$("#s3list").jqGrid('navButtonAdd', '#s3pager', {
        caption: "Update",
	 	title:"Update",
        buttonicon: "ui-icon-pencil",
        id: 'saveAllButton',
        onClickButton: function () {
        	if (listEditedRowID.length > 0) {
        		openConfirmBox();
        	} else {
        		alert("No updated row!!!");
        	}
            
        }
    });
	
	jQuery("#s3list").jqGrid('navButtonAdd','#s3pager',{
		caption:"Restore",
		buttonicon : 'ui-icon-restore',
		onClickButton : function () {
			if (lastEditedRow >= 0 && $("tr#"+lastEditedRow).attr("editable") == "1") {
				jQuery('#s3list').jqGrid('restoreRow', lastEditedRow);
				
				// remove edited row
				for (var j = listEditedRowID.length - 1; j >= 0; j--) {
					if (listEditedRowID[j] == lastEditedRow) {
						listEditedRowID.splice(j, 1);
					}
				}
				
				lastEditedRow = -1;
				
				// trigger scrolling keep current view
				var gridScroll = $('div.ui-jqgrid-bdiv');
				gridScroll.scrollLeft(1);
			}
			/*
			var rowids = jQuery('#s3list').getGridParam('selarrrow').slice(0);
			if (rowids) {
				for (var i = 0; i < rowids.length; i++) {
					jQuery('#s3list').jqGrid('restoreRow', rowids[i]);
					//jQuery('#s3list').jqGrid('resetSelection', rowids[i]);
					
					jQuery('#s3list').jqGrid("setSelection",rowids[i],false);
					
					for (var j = listEditedRowID.length - 1; j >= 0; j--) {
						if (listEditedRowID[j] == rowids[i]) {
							listEditedRowID.splice(j, 1);
						}
					}
					
					//$("jqg_s3list_" + rowids[i]).click();
				}
				
			}
			*/
		}
	});
	
	jQuery("#s3list").jqGrid('filterToolbar',{searchOnEnter : false, defaultSearch : "cn"});
	
	jQuery("#s3list").jqGrid('setFrozenColumns');
	//jQuery("#s3list").p._complete.call(jQuery("#s3list")); 
}


function addReleasedHoldSearchCriteria() {
	// default requirement to reload grid.
	var params = {datatype:'json', page:1, search : true};
	params.postData = getCurrentCondition4ReleasedHold();
	jQuery("#s3list").jqGrid("clearGridData", true).setGridParam(params);
}

function clearPreviousPostData() {
	var postData = $("#s3list").jqGrid('getGridParam','postData');
    try {
    	delete postData['department'];
    	delete postData['prodarea'];
    	delete postData['priority'];
    	delete postData['customername'];
    	delete postData['holdcode'];
    	delete postData['holdreason'];
    	delete postData['holdcodereclas'];
    	delete postData['holdreclasreason'];
    	delete postData['holdendfrom'];
    	delete postData['holdendto'];
    	// clear filter
    	$("#s3list")[0].clearToolbar();
    	// update current time
    	jQuery("#s3list").setCaption("RELEASED HOLD " + displayNiceDateFormat(new Date()));
    } catch (e) { }
}
function searchReleasedHoldByFilter() {
	clearPreviousPostData();
	addReleasedHoldSearchCriteria();
	jQuery("#s3list").trigger("reloadGrid");
}

function sendData(url)
{	
	if (listEditedRowID.length>0)
		{
			var sendData = parseData();
			showSavingMessage();
			$.ajax({
		        type: "POST", 		
		        url: url, 		
		        data: {releasedHolds:sendData},
		        processdata: true, 	
		        dataType: 'json',
//		        async:false,
		        success: function (json) {
		        	hideSavingMessage();
		            
		            //clean listEditedRowID
		            listEditedRowID = new Array();
		            
		            // reload data
		            searchReleasedHoldByFilter();
		        },
		        error: function()
		        {
		        	hideSavingMessage();
		        	alert('There are some errors! Your data have not been updated!');
		        	returnToEditMode();
		        }
		    });
		}
}
function parseData()
{
	var result = '{';
	for (var i=0;i<listEditedRowID.length-1; ++i)
		{
			var data2 = JSON.stringify(getGridData(listEditedRowID[i]), null, 2);
			result = result + i + ':' + data2+ ',';
		}
	var data2 = JSON.stringify(getGridData(listEditedRowID[listEditedRowID.length-1]), null, 2);
	result = result + (listEditedRowID.length-1) + ':' + data2+ '}';
	return result;
}


function getGridData(rowId)
{
	return $("#s3list").jqGrid('getRowData',rowId);
}

function returnToEditMode()
{
	//change row in listEditedRowID to edit mode
	for (var i=0;i<listEditedRowID.length;++i)
	{
		$("#s3list").jqGrid('editRow',listEditedRowID[i]);
	}
}
function showSavingMessage() 
{
	$("#load_s3list").html('<font color="#2E6E9E"> Updating ...</font>');
	$("#refresh_s3list").addClass('ui-state-disabled');
	$(".loading").css("display", "block");
	$("#lui_"+$("#s3list")[0].p.id).show();
}
function hideSavingMessage() 
{
	$("#load_s3list").html('<font color="#2E6E9E"> Loading ...</font>');
	$("#refresh_s3list").removeClass('ui-state-disabled');
	$(".loading").css("display", "none");
	$("#lui_"+$("#s3list")[0].p.id).hide();
}
$(function() {
	declareConfirmBox('comfirmDialogHandler');
});
function comfirmDialogHandler()
{
	for (var i = 0; i < listEditedRowID.length; i++) {
    	if ($("tr#"+listEditedRowID[i]).attr("editable") === "1") {
    		//save to client
			$('#s3list').jqGrid('saveRow', listEditedRowID[i]);
		}
    }
	sendData('updateReleasedHold.do');
    
}